#!/bin/bash

set -xuo pipefail

#Set the options of the getopt command
# NOTE: local-build is optional
format=$(getopt -n "$0" -l "base-image:,image-tag:,source-dir:,build-type:,use-cuda:,local-build" -- -- "$@")
if [ $? != 0 ]; then
    echo "Getopt failed"
    exit 1
fi

if [ $# -lt 6 ]; then
   echo "Wrong number of arguments passed."
   exit
fi
eval set -- "$format"

#Read the argument values
while [ $# -gt 0 ]
do
     case "$1" in
          --base-image)  BASE_IMAGE="$2"; shift;;
          --image-tag)   IMAGE_TAG="$2"; shift;;
          --source-dir)  SOURCE_DIR="$2"; shift;;
          --build-type)  BUILD_TYPE="$2"; shift;;
          --use-cuda)    USE_CUDA="$2"; shift;;
          --local-build) LOCAL_BUILD="1";;
          --) shift; break;;
          *) echo "Invalid option: $1"; exit 1;;
     esac
     shift;
done

set -e

# Avoid build errors due to a missing .creds folder
mkdir -p "$SOURCE_DIR/.creds"

export DOCKER_BUILDKIT=1

if [[ -z "${LOCAL_BUILD+x}" ]]; then
     docker build \
          --build-arg BASE_IMAGE="$BASE_IMAGE" \
          --build-arg AWS_REGION="$AWS_REGION" \
          --build-arg AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" \
          --build-arg AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" \
          --build-arg AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" \
          --build-arg GITHUB_TOKEN="$GITHUB_TOKEN" \
          --build-arg USE_CUDA="$USE_CUDA" \
          --build-arg BUILD_TYPE="$BUILD_TYPE" \
          --progress=plain \
          --tag="$IMAGE_TAG" \
          -f "$SOURCE_DIR/continuous_integration/Dockerfile" "$SOURCE_DIR";
else
     docker build \
          --target setup \
          --build-arg BASE_IMAGE="$BASE_IMAGE" \
          --build-arg USE_CUDA="$USE_CUDA" \
          --build-arg BUILD_TYPE="$BUILD_TYPE" \
          --progress=plain \
          --tag="$IMAGE_TAG" \
          -f "$SOURCE_DIR/continuous_integration/Dockerfile" "$SOURCE_DIR";
fi
